<template>
  <div class="cartbox">
    <table>
      <tr>
        <td>
          <input type="checkbox" v-model="allchecked" @change="checkedAll" />
        </td>
        <td>编号</td>
        <td>名称</td>
        <td>单价</td>
        <td>数量</td>
        <td>金额</td>
        <td>操作</td>
      </tr>
      <tr v-for="(goods, index) in shopCars" :key="index">
        <td>
          <input type="checkbox" v-model="goods.isChecked" 
            @change="backCheckedAll"/>
        
        </td>
        <td>{{ goods.goodsId }}</td>
        <td>{{ goods.goodsname }}</td>
        <td>{{ goods.goodsprice }}</td>
        <td>
          <input type="button" value="-" @click="reduceCount(index)" />
          {{ goods.count }}
          <input type="button" value="+" @click="addCount(index)" />
        </td>
        <td>{{ goods.goodsprice * goods.count }}</td>
        <td>
          <input type="button" value="删除" @cilck="deleteGoods(index)" />
        </td>
      </tr>
      <tr>
        <td colspan="7">总计：¥{{ totalMoney() }}</td>
      </tr>
    </table>

    <p>- 猜你喜欢 -</p>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "cartgoods",
  data() {
    return {
        allchecked:false,
      goodsinfo: "",
      goods: "",
      shopCars:[],
    };
  },
  methods: {
    checkedAll() {
      // console.log(this.allchecked);
      this.shopCars.forEach((goods) => {
        goods.isChecked = this.allchecked;
      });
    },
    addCount(idx) {
      this.shopCars[idx].count++;
    },
    reduceCount(idx) {
      if (this.shopCars[idx].count - 1 <= 0) {
        his.shopCars[idx].count = 1;
        return;
      }
      this.shopCars[idx].count--;
    },
    deleteGoods() {
        console.log ("1")
         this.shopCars.splice(idx, 1);
          axios.post(
        "/cart",this.shopCars
      ).then((res) => {
        console.log("res", res);
        if (res.data) {
          this.$toast.success("加入成功");
        } else {
          this.$toast.success("加入失败");
        }
      });
    
    
    },

    totalMoney() {
      let money = 0;
      this.shopCars.forEach((goods) => {
         
        if (goods.isChecked) {
          money += goods.count * goods.goodsprice;
        }
      });
      return money;
    },
    backCheckedAll() {
      this.allchecked = this.shopCars.every((goods) => goods.isChecked);
    },
  },
//   allchecked
  created() {
    axios({
      url: "/cart",
    }).then((res) => {
      this.shopCars = res.data;
    
    });
  },
};
</script>

<style scoped>
.cartbox {
  padding: 0.5rem 0;
  margin-left: 0.2rem;
}
.cartbox p {
  width: 100%;
  text-align: center;
  font-weight: 700;
  font-size: 0.2rem;
}
</style>


